package com.bj.disc.service

import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.util.Base64
import com.bj.disc.base.App
import com.bj.disc.bean.MessageResponse
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.File
import java.io.IOException
import java.io.RandomAccessFile
import java.util.concurrent.LinkedBlockingQueue

class MessageService : Service() {
    var DOWNLOAD_FILE_STATIC_DIR = "${App.instance.filesDir.absolutePath}/"
    private val dataQueue = LinkedBlockingQueue<MessageResponse>()

    override fun onCreate() {
        super.onCreate()
        var dir = File(DOWNLOAD_FILE_STATIC_DIR)
        if (!dir.exists()) {
            dir.mkdirs()
        }
        // 启动数据处理线程
        startDataProcessingThread()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (intent != null && intent.hasExtra("data")) {
            val messageResponse = intent.getSerializableExtra("data") as? MessageResponse
            messageResponse?.let {
                // 将数据放入队列
                dataQueue.offer(it)
            }
        }

        return START_STICKY
    }

    private fun startDataProcessingThread() {
        GlobalScope.launch(Dispatchers.IO) {
            while (true) {
                synchronized(MessageService::class.java){
                try {
                    val messageResponse = dataQueue.take() // 从队列取出数据
                    // 异步处理数据
                    if(null!=messageResponse) {
                        writeToStorage(messageResponse)
                    }
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
                }
            }
        }
    }

    private fun writeToStorage(messageResponse: MessageResponse) {
        // 将数据写入文件的逻辑
        // 这里使用 RandomAccessFile 实现断点续传写入
        try {
            if (messageResponse.chatUuid == null) {
                // 如果 chatUuid 未初始化，不进行写入
                return
            }
            val audioData = Base64.decode(
                messageResponse.data?.replace("data:audio/mp3;base64,", ""),
                Base64.DEFAULT
            )

            val fileName = messageResponse.chatUuid
            val file = File(DOWNLOAD_FILE_STATIC_DIR, fileName+".mp3")
            if(!file.exists()){
                file.createNewFile()
            }
            val randomAccessFile = RandomAccessFile(file, "rw")
            // 将文件指针移动到文件末尾
            randomAccessFile.seek(randomAccessFile.length())
            randomAccessFile.write(audioData)
            randomAccessFile.close()

        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    override fun onBind(intent: Intent): IBinder? {
        return null
    }
}
